package com.watson.influxDB.controller;

import com.watson.influxDB.emtity.LogInfo;
import com.watson.tool.utils.Result;
import org.influxdb.InfluxDB;
import org.influxdb.dto.BoundParameterQuery;
import org.influxdb.dto.Point;
import org.influxdb.dto.QueryResult;
import org.influxdb.impl.InfluxDBResultMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * // todo
 *
 * @author: llun
 * @date: 2022/1/25 14:06
 * @version: 1.0
 */
@RestController
public class InfluxdbController {
    private static final Logger logger = LoggerFactory.getLogger(InfluxdbController.class);
    /**
     * //注入influxDB
     */
    @Resource
    private InfluxDB influxDB;

    //    @Scheduled(fixedRate = 5000)
    public void writeQPS() {
        // 模拟要上报的统计数据
        int count = (int) (Math.random() * 100);

        Point point = Point.measurement("ApiQPS")     // ApiQPS表
                .tag("url", "/hello")  // url字段
                .addField("count", count)        // 统计数据
                .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)  // 时间
                .build();

        // 往test库写数据
        influxDB.write("mydata", "autogen", point);

        logger.info("上报统计数据：" + count);
    }

    @GetMapping("writePoint")
    public Result insertPoint() {
        try {
            influxDB.setDatabase("mydb");
            //新建一个Point,指定表名，和tag以及field
            //由于是链式调用可以增加多个Tag和Field
            Point point = Point.measurement("temperature")
//                    .tag("host", "server03")
//                    .tag("region", "zh-east")
                    .addField("value", 11.0)
                    .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
                    .build();
            influxDB.write(point);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result().error("失败");
        }
        return new Result().ok("success");
    }


    @GetMapping("writePoint2")
    public Result insertPoint2() {
        try {
            influxDB.setDatabase("mydb");
            LogInfo logInfo = LogInfo.builder()
                    .level("1")
                    .module("module")
                    .deviceId("1217")
                    .msg("hello")
                    .build();
            Point point = Point.measurementByPOJO(logInfo.getClass())
                    .addFieldsFromPOJO(logInfo)
                    .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
                    .build();
            influxDB.write(point);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result().error("failed");
        }

        return new Result().ok("success");
    }


    @GetMapping("get")
    public List<LogInfo> get(Integer pageNumber, Integer pageSize) {
//        try(InfluxDB influxDB = InfluxDBFactory.connect(baseUrl, username, password)) {
        try {
            InfluxDBResultMapper resultMapper = new InfluxDBResultMapper();
            QueryResult queryResult = influxDB.query(BoundParameterQuery.QueryBuilder
//                    .newQuery("select * from logInfo where device_id=$device_id  limit 1 OFFSET 1")
//                    .newQuery("select * from logInfo where device_id=$device_id order by time asc tz('Asia/Shanghai') ")
                    .newQuery("select * from logInfo where device_id=$device_id order by time asc  limit 2 OFFSET 1")
                    .forDatabase("mydb")
//                    .bind("pointName", "load")
                    .bind("device_id", "1212")
//                    .bind("startDate", startDate)
//                    .bind("endDate", endDate)
                    .create());
            List<LogInfo> logInfos = resultMapper.toPOJO(queryResult, LogInfo.class);
            return logInfos;
        } catch (Exception e) {
            logger.error("查询发生错误{}" + e.getStackTrace());
            e.printStackTrace();
        }


//        String pageQuery = " LIMIT " + request.getPageSize() + " OFFSET " + ((request.getPageNum() - 1) * request.getPageSize());
//        String queryCondition = " where eid= '" + list.get(i) + "'";// 查询条件
//        String queryCmd = "SELECT time, eid, co2, formaldehyde FROM"
//                + " composition"
//                + queryCondition
//                + " ORDER BY time DESC"
//                + pageQuery;
//         // 开始查询
//        QueryResult queryResult = influxDB.query(queryCmd);
//        System.out.println(queryResult);

        return null;
    }
}
